package library.sdk.demo.parent;

import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerViewOptions;
import com.mapbox.mapboxsdk.annotations.PolygonOptions;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.zhd.communication.DeviceManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import library.sdk.demo.R;
import mapbox.MapFragment;
import rtk.RtkData;
import widget.annotation.ViewInject;
import widget.utils.FileUtils;
import widget.utils.Tips;
import widget.utils.ViewUtils;

/**
 * Created by apple on 2017/5/26.
 */

public abstract class AbsMapActivity extends ParentActivity {

    @ViewInject(R.id.activity_main_toolbar)
    protected Toolbar mToolbar;

    @ViewInject(R.id.activity_map_gps_info)
    protected TextView mTextViewInfo;

    @ViewInject(R.id.activity_map_locate)
    protected ImageButton mLocate;

    @ViewInject(R.id.activity_map_btn_conn)
    protected Button mConn;
    @ViewInject(R.id.activity_map_btn_start)
    protected Button mStart;
    @ViewInject(R.id.activity_map_btn_end)
    protected Button mEnd;
    @ViewInject(R.id.activity_map_btn_save)
    protected Button mSave;
    @ViewInject(R.id.activity_map_btn_clear)
    protected Button mClear;

    private MapFragment mMapFragment;

    private final List<Marker> list = new ArrayList<>();
    protected boolean isLogging = false;

    private int showingIndex = 0;

    @Override
    protected Object inflateView() {
        return R.layout.activity_map;
    }

    @Override
    protected void initView(View anchor) {
        ViewUtils.inject(this, AbsMapActivity.class);

        setSystemBar();
        setSupportActionBar(mToolbar);

        mMapFragment = MapFragment.install(this, R.id.activity_map_frame);

        mClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearMarker();
            }
        });
        mStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isLogging = true;
                showingIndex = 0;
                showMarker();
            }
        });
        mEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isLogging = false;
            }
        });
        mSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });

        mLocate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogging) {
                    showingIndex++;
                    showingIndex = showingIndex > 2 ? 0 : showingIndex;
                    MapboxMap mapboxMap = mMapFragment.getMapboxMap();
                    if (showingIndex == 0) {
                        mapboxMap.clear();
                        showMarker();
                    } else if (showingIndex == 1) {
                        mapboxMap.clear();
                        showPolygon();
                    } else {
                        mapboxMap.clear();
                        showPolygon();
                        showMarker();
                    }
                } else {
                    Tips.warn(getActivity(), "录制时不能切换");
                }
            }
        });
    }

    public void showPolygon() {
        try {
            MapboxMap mapboxMap = mMapFragment.getMapboxMap();
            PolygonOptions options = new PolygonOptions();
            synchronized (list) {
                for (Marker marker : list) {
                    options.add(marker.getPosition());
                }
            }
            options.alpha(0.67F);
            options.fillColor(Color.MAGENTA);
            options.strokeColor(Color.WHITE);
            mapboxMap.addPolygon(options);
        } catch (Exception e) {

        }
    }

    public void showMarker() {
        try {
            MapboxMap mapboxMap = mMapFragment.getMapboxMap();
            synchronized (list) {
                for (Marker marker : list) {
                    mapboxMap.addMarker(new MarkerViewOptions()
                            .position(marker.getPosition())
                            .snippet(marker.getSnippet()));
                }
            }
        } catch (Exception e) {

        }
    }

    private File getSaveDir() {
        return new File(getObbDir() + "/" + getClass().getSimpleName());
    }

    private void save() {
        try {
            MapboxMap mapboxMap = mMapFragment.getMapboxMap();
            JSONArray array = new JSONArray();
            for (Marker marker : mapboxMap.getMarkers()) {
                LatLng position = marker.getPosition();
                JSONObject item = new JSONObject();
                item.put("lat", position.getLatitude());
                item.put("lng", position.getLongitude());
                item.put("snip", marker.getSnippet());
                array.put(item);

            }
            File file = new File(getSaveDir() + "/" + System.currentTimeMillis() + ".json");
            if (FileUtils.saveText(file, array.toString()))
                Tips.warn(this, "已保存至 : " + file);
            else
                Tips.warn(this, "保存失败 ");

        } catch (Exception e) {
            Tips.warn(this, e.getMessage());
        }
    }

    public void clearMarker() {
        try {
            MapboxMap mapboxMap = mMapFragment.getMapboxMap();
            mapboxMap.clear();
            synchronized (list) {
                list.clear();
            }
        } catch (Exception e) {

        }
    }

    public void addMarker(RtkData data) {
        if (!isLogging)
            return;
        try {
            MapboxMap mapboxMap = mMapFragment.getMapboxMap();
//            for (Marker marker : list) {
//                LatLng position = marker.getPosition();
//                if (position.getLongitude() == latLng.getLongitude() && position.getLatitude() == latLng.getLatitude()) {
//                    return;
//                }
//            }
            LatLng latLng = new LatLng(data.getLatitude(), data.getLongitude());
            Marker marker = mapboxMap.addMarker(new MarkerViewOptions()
                    .position(latLng)
                    .snippet("纬度:" + data.getLatitude() + "\n"
                            + "精度:" + data.getLongitude() + "\n"
                            + "高度:" + data.getAltitude() + "\n"
                            + "方向:" + data.getBearing() + "\n"
                            + "精度:" + data.getAccuracy() + "\n"
                            + "解算:" + data.getStringMode()));
            if (mapboxMap.getMarkers().size() == 1)
                mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
            else
                mapboxMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            synchronized (list) {
                list.add(marker);
            }
        } catch (Exception e) {
        }
    }

    public void addMarker(LatLng latLng, String mode, String accuracy) {
        if (!isLogging)
            return;
        try {
            MapboxMap mapboxMap = mMapFragment.getMapboxMap();
//            for (Marker marker : list) {
//                LatLng position = marker.getPosition();
//                if (position.getLongitude() == latLng.getLongitude() && position.getLatitude() == latLng.getLatitude()) {
//                    return;
//                }
//            }
            Marker marker = mapboxMap.addMarker(new MarkerViewOptions()
                    .position(latLng)
                    .snippet("纬度:" + latLng.getLatitude() + "\n"
                            + "精度:" + latLng.getLongitude() + "\n"
                            + "高度:" + latLng.getAltitude() + "\n"
                            + "精度:" + accuracy + "\n"
                            + "解算:" + mode));
            if (mapboxMap.getMarkers().size() == 1)
                mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
            else
                mapboxMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            synchronized (list) {
                list.add(marker);
            }
        } catch (Exception e) {
        }
    }

    public void addMarker(double lat, double lng, String snip) {
        try {
            LatLng latLng = new LatLng(lat, lng);
            MapboxMap mapboxMap = mMapFragment.getMapboxMap();
            Marker marker = mapboxMap.addMarker(new MarkerViewOptions()
                    .position(latLng)
                    .snippet(snip));
            synchronized (list) {
                list.add(marker);
            }
            if (mapboxMap.getMarkers().size() == 1)
                mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
        } catch (Exception e) {
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_map, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_map_0:
                mMapFragment.toggleLayer("tile-google");
                break;
            case R.id.menu_map_1:
                mMapFragment.toggleLayer("title-st");
                break;
            case R.id.menu_map_2:
                showHistoryList();
                break;
            default:
                break;
        }
        return true;

    }

    private void showHistoryList() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("历史记录");

        File dir = getSaveDir();
        String[] names = dir.list();
        Arrays.sort(names, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return -o1.compareTo(o2);
            }
        });
        builder.setItems(names, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                File file = new File(dir, names[which]);
                try {
                    String text = FileUtils.readTxtFile(file.getCanonicalPath());
                    clearMarker();
                    JSONArray array = new JSONArray(text);
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject obj = array.getJSONObject(i);

                        double lat = obj.getDouble("lat");
                        double lng = obj.getDouble("lng");
                        String snip = obj.getString("snip");
                        addMarker(lat, lng, snip);
                    }
                    dialog.dismiss();
                } catch (Exception e) {
                    Tips.warn(getActivity(), "加载出错" + e.getMessage());
                }
            }
        });
        builder.create().show();
    }

    public void disableBle() {
        if (BluetoothAdapter.getDefaultAdapter() != null)
            BluetoothAdapter.getDefaultAdapter().disable();
    }

    public void enableBle() {
        if (BluetoothAdapter.getDefaultAdapter() != null)
            BluetoothAdapter.getDefaultAdapter().enable();
    }

    @Override
    public void finish() {
        super.finish();
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        DeviceManager.getInstance().cancelConnect();
        finish();
    }
}
